<template>
  <div style="width: 600px; margin: 20px auto;">
    <el-dialog :title="dialogTitle" :visible.sync="localShow" @close="insertClose">
    <el-form
        :model="admin"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        size="medium"
        label-position="right"
    >
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="adminName">
        <el-input
            v-model="admin.adminName"
            placeholder="请输入真实姓名"
            clearable
        ></el-input>
      </el-form-item>

      <!-- 电话 -->
      <el-form-item label="电话" prop="phone">
        <el-input
            v-model="admin.phone"
            @blur="generatePassword"
            placeholder="请输入11位手机号码"
            maxlength="11"
            clearable
        ></el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-form-item label="密码" prop="adminPass">
        <el-input
            v-model="admin.adminPass"
            :disabled="true"
            placeholder="自动生成初始密码"
        ></el-input>
        <div class="tip-text">初始密码为姓名拼音首字母+手机号后4位</div>
      </el-form-item>
      <!-- 性别 -->
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="admin.gender">
          <el-radio :label="'男'" >男</el-radio>
          <el-radio :label="'女'">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input
            v-model="admin.email"
            placeholder="请输入邮箱"
            clearable
        ></el-input>
      </el-form-item>

      <!-- 身份证号 -->
      <el-form-item label="身份证号" prop="inNum">
        <el-input
            v-model="admin.inNum"
            placeholder="请输入18位身份证号"
            maxlength="18"
            clearable
        ></el-input>
      </el-form-item>

      <!-- 身份证照片 -->
      <div class="form-row">
        <el-form-item label="身份证正面" prop="photoRight" class="form-item">
          <el-upload
              :action="$basePath+'admin/uploadPic'"
              :headers="headers"
              :accept="allowPicExts"
              :show-file-list="false"
              :before-upload="beforeFrontPicUpload"
              :on-success="handleFrontPicSuccess"
              list-type="picture-card"
          >
            <img v-if="imageFrontUrl" :src="imageFrontUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="身份证反面" prop="photoBack" class="form-item">
          <el-upload
              :action="$basePath+'admin/uploadPic'"
              :headers="headers"
              :accept="allowPicExts"
              :show-file-list="false"
              :before-upload="beforeVersoPicUpload"
              :on-success="handleVersoPicSuccess"
              list-type="picture-card"
          >
            <img v-if="imageVersoUrl" :src="imageVersoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </div>
      <el-form-item label="职位">
        <el-select v-model="roleId" placeholder="请选择职位">
          <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleCreate">立即创建</el-button>
        <el-button @click="handleCancle">取消</el-button>
      </el-form-item>
    </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { pinyin } from "pinyin-pro";
export default {
  name: "StaffInsertView",
  props: {
    dialogTitle: {
      type: String,
      default: '添加员工' // 默认值
    },
    message:{
      type:Boolean,
    },
  },
  watch: {
    message(val){
      this.localShow = val;
    },
  },
  data() {
    return {
      admin:{
        adminName:'',
        adminPass:'',
        phone:'',
        email:'',
        gender:'男',
        inNum:'',
        photoRight:'',
        photoBack:'',
      },
      originalPhone:'',
      originalInNum:'',
      localShow:false,
      imageFrontUrl:"",
      imageVersoUrl:'',
      headers:{"token":window.localStorage.token},
      allowPicExts:'.jpg,.jpeg,.png,.webp,.gif',
      maxFileSize:102400*1024*5,
      roleId:1,
      roleList:[],
      rules:{
        adminName:[
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        phone:[
          { required: true, message: "电话号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的11位手机号码",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              if (value === this.originalPhone) {
                callback();
                return;
              }
              if (!value) return callback(new Error("请输入手机号码"));
              if (!/^1[3-9]\d{9}$/.test(value)) {
                return callback(new Error("手机号码格式不正确"));
              }
              this.axios.get("/admin/selectAdminByPhone/"+value)
                  .then(res => {
                    if(res.data.admin){
                      callback(new Error("该手机号已注册"));
                    }
                    else {
                      callback();
                    }
                  });
            },
            trigger: "blur"
          }
        ],
        email:[
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱格式（如：example@domain.com）",
            trigger: ["blur", "change"]
          },
          {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: "请输入有效的邮箱地址",
            trigger: "blur"
          }
        ],
        gender:[
          { required: true, message: "请选择性别", trigger: "change" },
        ],
        inNum:[
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          { pattern: /^\d{17}[\dXx]$/, message: "请输入正确的18位身份证号", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value === this.originalInNum) {
                callback();
                return;
              }
              if (!value) return callback(new Error("请输入身份证号码"));
              if (!/^\d{17}[\dXx]$/.test(value)) {
                return callback(new Error("格式不正确"));
              }
              this.axios.get("/admin/selectAdminByInNum/"+value)
                  .then(res => {
                    if(res.data.admin){
                      callback(new Error("请输入自己的身份证号码"));
                    }
                    else {
                      callback();
                    }
                  });
            },
            trigger: "blur"
          }

        ],
        photoRight:[
          { required: true, message: "未检测到照片", trigger: "change" },
        ],
        photoBack:[
          { required: true, message: "未检测到照片", trigger: "change" },
        ],

      }

    }
  },
  created() {
    this.getAdminRole();
  },
  methods: {
    getAdminRole() {
      this.axios.get("/admin/adminRole").then(res => {
        this.roleList = res.data.roleList;
      });
    },
    update(row){
      this.admin = JSON.parse(JSON.stringify(row.admin));
      this.roleId = JSON.parse(JSON.stringify(row.roleId));
      this.originalPhone = this.admin.phone;
      this.originalInNum = this.admin.inNum;
    },
    generatePassword(){
     if (this.admin.adminName && this.admin.phone){
       let initials;
       if (/[\u4e00-\u9fa5]/.test(this.admin.adminName)) {
         const fullPinyin = pinyin(this.admin.adminName, {
           toneType: 'none',
           type: 'string'
         });
         initials = fullPinyin                // "chenchuang"
             .replace(/(^|[^a-z])([a-z])[a-z]*/g, '$2')
             .toUpperCase()
             .toLowerCase();
       } else {
         initials = this.admin.adminName.slice(0, 2).toLowerCase();
       }
       const phonePart = this.admin.phone.slice(-4);
       this.admin.adminPass = initials+phonePart; // 如 "cc3456"
     }
    },
    handleCreate() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          var url = '';
          this.admin.id ? url='/admin/update' : url='/admin/insert'
          this.axios.post(url, this.admin, {
            params: {roleId:this.roleId}
          })
              .then(res => {
                if (res.data.msg == "操作成功") {
                  this.$message.success(
                    this.admin.id ? '修改成功' : '添加成功'
                  );
                  this.$refs.ruleForm.resetFields();
                  this.insertClose();
                }
                else {
                  this.$message.error(
                      this.admin.id ? '修改失败' : '添加失败'
                  );
                  this.$refs.ruleForm.resetFields();
                  this.insertClose();
                }
              });
        }
      });
    },
    handleCancle() {
      this.$refs.ruleForm.resetFields();
      this.insertClose();
    },
    insertClose(){
      this.localShow = false;
      this.admin = Object.assign({}, this.$options.data().admin);
      this.imageFrontUrl = this.admin.imageFrontUrl;
      this.imageVersoUrl = this.admin.imageVersoUrl;
      this.$refs.ruleForm.resetFields();
      this.$emit("close",false);

    },
    //上传之前可以对类型和大小进行校验，返回true执行上传，返回false不执行上传
    beforeFrontPicUpload(file) {
      this.imageFrontUrl="";
      //名字名最后的点的位置
      let dotIndex = file.name.lastIndexOf(".");
      //没有扩展名
      if(dotIndex == -1){
        this.$message.error("上传图片只能是("+this.allowPicExts+")格式")
        return false;
      }
      //扩展名
      let ext = file.name.substring(dotIndex);
      //,.jpg,.jpeg,.png,.webp,.gif,           ,.webp,
      if(!(","+this.allowPicExts+",").includes(","+ext+",")){
        this.$message.error("上传图片只能是("+this.allowPicExts+")格式")
        return false;
      }
      if(file.size > this.maxFileSize){
        this.$message.error("上传图片最大不能超过"+this.maxFileSize/1024+"KB")
        return false;
      }
      return true;
    },
    beforeVersoPicUpload(file) {
      this.imageVersoUrl="";
      //名字名最后的点的位置
      let dotIndex = file.name.lastIndexOf(".");
      //没有扩展名
      if(dotIndex == -1){
        this.$message.error("上传图片只能是("+this.allowPicExts+")格式")
        return false;
      }
      //扩展名
      let ext = file.name.substring(dotIndex);
      //,.jpg,.jpeg,.png,.webp,.gif,           ,.webp,
      if(!(","+this.allowPicExts+",").includes(","+ext+",")){
        this.$message.error("上传图片只能是("+this.allowPicExts+")格式")
        return false;
      }
      if(file.size > this.maxFileSize){
        this.$message.error("上传图片最大不能超过"+this.maxFileSize/1024+"KB")
        return false;
      }
      return true;
    },
    handleFrontPicSuccess(res, file) {
      if(res.code == 500){
        this.$message.error("上传失败");
        return false;
      }
      //this.imageUrl = URL.createObjectURL(file.raw);
      this.imageFrontUrl = this.$basePath+"static/uploadImages/"+res.fileName;
      this.admin.photoRight = res.fileName;

    },
    handleVersoPicSuccess(res, file) {
      if(res.code == 500){
        this.$message.error("上传失败");
        return false;
      }
      //this.imageUrl = URL.createObjectURL(file.raw);
      this.imageVersoUrl = this.$basePath+"static/uploadImages/"+res.fileName;
      this.admin.photoBack = res.fileName;

    },
  }
}
</script>
<style>
.form-row {
  display: flex;
  gap: 16px; /* 控制两个输入框之间的间距 */
  margin-bottom: 16px; /* 控制每行之间的间距 */
}

.form-item {
  flex: 1; /* 每个输入框占相等的宽度 */
}

.full-width-item {
  flex: 2; /* 如果是单独一行，可以调整为需要的宽度比例，这里设置为 2 或 1 都可以 */
  width: 100%; /* 确保独占一行 */
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>